/*
Copyright 2011 Raymond Giorgi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package edu.pitt.cs3530.threads;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import edu.pitt.cs3530.identifier.HandshakeInfo;
import edu.pitt.cs3530.messages.AbstractMessage;
import edu.pitt.cs3530.messages.HandshakeMessage;
import edu.pitt.cs3530.messages.UtilizationMessage;
import edu.pitt.cs3530.misc.UtilizationStatistics;
import edu.pitt.cs3530.objects.utilization.SimpleUtilization;
import edu.pitt.cs3530.xml.ApplicationServerConfig;

public class Connector {
	private static Socket socket = null;

	private static class SendUtilization extends Thread {
		@Override
		public void run() {
			try {
				if (socket == null) {
					socket = connect();
				}
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (socket != null) {
				while (true) {
					SimpleUtilization simpleUtilization = UtilizationStatistics
							.getAverage();
					AbstractMessage message = new UtilizationMessage(
							HandshakeInfo.instance.getHostname(),
							ApplicationServerConfig.getInstance()
									.getFullServerName(), simpleUtilization);
					sendMessage(message);
					try {
						sleep(ApplicationServerConfig.getInstance()
								.getUtilSendTimeout());
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}
	}

	public static class RecieveMessage extends Thread {
		@Override
		public void run() {
			while (true) {
				try {
					ObjectInputStream stream = new ObjectInputStream(socket
							.getInputStream());
					AbstractMessage message = (AbstractMessage) stream
							.readObject();
					message.processMessage();
				} catch (IOException e) {
					// TODO Auto-generat
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public static void start() throws UnknownHostException, IOException {
		connect();
		new SendUtilization().start();
		new RecieveMessage().start();
	}

	public static Socket connect() throws UnknownHostException, IOException {
		socket = new Socket(ApplicationServerConfig.getInstance()
				.getFullServerName(), ApplicationServerConfig.getInstance()
				.getPort());
		sendHandshakeMessage();
		try {
			// Make sure network delay doesn't prevent this message from getting
			// through first
			Thread.sleep(50);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return socket;
	}

	public static void sendHandshakeMessage() throws IOException {
		HandshakeInfo info = HandshakeInfo.instance.clone();
		AbstractMessage message = new HandshakeMessage(info.getHostname(),
				ApplicationServerConfig.getInstance().getFullServerName(), info);
		sendMessage(message);
	}

	public static void sendMessage(AbstractMessage message) {
		try {
			ObjectOutputStream oos = new ObjectOutputStream(socket
					.getOutputStream());
			oos.writeObject(message);
			oos.flush();
		} catch (IOException e) {
			try {
				socket = connect();
				ObjectOutputStream oos = new ObjectOutputStream(socket
						.getOutputStream());
				oos.writeObject(message);
				oos.flush();
			} catch (UnknownHostException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
}
